package com.qfedu.fmmall.service.impl;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qfedu.fmmall.common.status.ResStatus;
import com.qfedu.fmmall.common.vo.ResultVO;
import com.qfedu.fmmall.dao.CategoryMapper;
import com.qfedu.fmmall.service.CategoryService;
import com.qfedu.fmmall.vo.CategoryVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author : yanBin
 * @date :2021/12/14 16:48
 */
@Service
public class CategoryServiceImpl implements CategoryService {

    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public ResultVO selectAllCategory() {
        List<CategoryVO> categoryVOS = null;
        try {
            String categoryVOS1 = (String) redisTemplate.boundValueOps("categoryVOS").get();
            if (StringUtils.isNotBlank(categoryVOS1)) {
                JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class, CategoryVO.class);
                categoryVOS = objectMapper.readValue(categoryVOS1, javaType);
            } else {

                categoryVOS = categoryMapper.selectAllCategory();
                if (CollectionUtils.isEmpty(categoryVOS)){
                    return new ResultVO(ResStatus.NO.getCode(), "没有此分类",null);
                }
                String categoryVOSJson = objectMapper.writeValueAsString(categoryVOS);
                redisTemplate.boundValueOps("categoryVOS").set(categoryVOSJson,1, TimeUnit.DAYS);
            }

            return new ResultVO(ResStatus.OK.getCode(), "分类查询成功", categoryVOS);
        } catch (Exception e) {
            return new ResultVO(ResStatus.NO.getCode(), e.getLocalizedMessage(), null);
        }


    }

    @Override
    public ResultVO listFirstLevelCategories() {
        try {
            return new ResultVO(ResStatus.OK.ordinal(), "查询指定一级类别成功", categoryMapper.selectFirstLevelCategories());
        } catch (Exception e) {
            return new ResultVO(ResStatus.NO.ordinal(), "查询指定一级类别失败", null);
        }
    }
}
